import {App, Modal, WorkspaceLeaf} from "obsidian";
import MyPlugin from "../../../../main";
import { StorageUtil } from "../../工具类/StorageUtil"; // 引入 StorageUtil

// 搜索历史管理器 - 改为持久化存储
class SearchHistoryManager {
	private static readonly STORAGE_KEY = 'search-history';
	private static readonly MAX_HISTORY_SIZE = 20;
	private app: App;
	private storage: StorageUtil;

	constructor(app: App, plugin: MyPlugin) {
		this.app = app;
		this.storage = new StorageUtil(app, plugin);
	}

	// 获取搜索历史
	async getHistory(): Promise<string[]> {
		return await this.storage.getData(SearchHistoryManager.STORAGE_KEY, []);
	}

	// 添加搜索记录
	async addSearch(query: string): Promise<void> {
		if (!query.trim()) return;

		let history = await this.getHistory();

		// 移除重复项
		history = history.filter(item => item !== query);

		// 添加到开头
		history.unshift(query);

		// 限制历史记录数量
		if (history.length > SearchHistoryManager.MAX_HISTORY_SIZE) {
			history = history.slice(0, SearchHistoryManager.MAX_HISTORY_SIZE);
		}

		// 持久化存储
		await this.storage.setData(SearchHistoryManager.STORAGE_KEY, history);
	}

	// 清空历史记录
	async clearHistory(): Promise<void> {
		await this.storage.setData(SearchHistoryManager.STORAGE_KEY, []);
	}

	// 删除单条历史记录
	async removeFromHistory(query: string): Promise<void> {
		let history = await this.getHistory();
		history = history.filter(item => item !== query);
		await this.storage.setData(SearchHistoryManager.STORAGE_KEY, history);
	}

	// 获取数组操作辅助类（可选，提供更方便的数组操作）
	getArrayHelper() {
		return this.storage.getArrayData<string>(SearchHistoryManager.STORAGE_KEY, []);
	}
}

// 修改命令注册函数，确保命令持久存在
export function 史锦泽的搜索框(this_: MyPlugin) {
	// 检查命令是否已经存在，避免重复注册
	const existingCommand = (this_.app as any).commands.commands['shijinze-search-modal'];
	if (existingCommand) {
		console.log('搜索框命令已存在，跳过重复注册');
		return;
	}

	// 注册命令
	this_.addCommand({
		id: 'shijinze-search-modal',
		name: '史锦泽的搜索框',
		callback: () => {
			try {
				new NativeSearchModal(this_.app, this_).open();
			} catch (error) {
				console.error('打开搜索框失败:', error);
				// 如果主要方式失败，尝试备用方案
				try {
					new AlternativeNativeSearchModal(this_.app, this_).open();
				} catch (fallbackError) {
					console.error('备用搜索框也失败:', fallbackError);
				}
			}
		}
	});

	// 确保命令在插件生命周期内持续存在
	console.log('史锦泽的搜索框命令已注册');
}

export default class NativeSearchModal extends Modal {
	private searchLeaf: WorkspaceLeaf | null = null;
	private originalParent: HTMLElement | null = null;
	private searchViewContainer: HTMLElement | null = null;
	private historyManager: SearchHistoryManager;
	private historyContainer: HTMLElement | null = null;
	private searchInputElement: HTMLInputElement | null = null;
	private plugin: MyPlugin;
	private originalEventHandlers: Map<HTMLElement, any[]> = new Map();
	private observers: (MutationObserver | any)[] = []; // 用于存储所有观察器

	constructor(app: App, plugin: MyPlugin) {
		super(app);
		this.plugin = plugin;
		this.setTitle(""); // 移除标题
		this.modalEl.addClass("native-search-modal");
		this.historyManager = new SearchHistoryManager(app, plugin);
	}

	onOpen() {
		const {contentEl} = this;

		// 设置模态框大小
		this.modalEl.style.width = "1200px";
		this.modalEl.style.height = "900px";
		this.modalEl.style.maxWidth = "95vw";
		this.modalEl.style.maxHeight = "90vh";

		// 移除默认的内边距
		contentEl.style.padding = "0";
		contentEl.style.height = "100%";

		// 隐藏和移除所有默认的模态框头部元素
		const closeButton = this.modalEl.querySelector('.modal-close-button') as HTMLElement;
		if (closeButton) {
			closeButton.style.display = 'none';
		}

		// 隐藏模态框标题区域
		const modalTitle = this.modalEl.querySelector('.modal-title') as HTMLElement;
		if (modalTitle) {
			modalTitle.style.display = 'none';
		}

		// 移除模态框头部的内边距和边距
		const modalHeader = this.modalEl.querySelector('.modal-header') as HTMLElement;
		if (modalHeader) {
			modalHeader.style.display = 'none';
		}

		// 确保内容区域占满整个模态框
		contentEl.style.position = 'absolute';
		contentEl.style.top = '0';
		contentEl.style.left = '0';
		contentEl.style.right = '0';
		contentEl.style.bottom = '0';

		this.embedNativeSearch(contentEl);
	}

	private async embedNativeSearch(contentEl: HTMLElement) {
		try {
			// 方法1：查找现有的搜索视图
			this.searchLeaf = this.app.workspace.getLeavesOfType('search')[0];
			await this.moveExistingSearchView(contentEl);
		} catch (error) {
			console.error('嵌入原生搜索失败:', error);
			this.showError(contentEl, error);
		}
	}

	private async moveExistingSearchView(contentEl: HTMLElement) {
		if (!this.searchLeaf || !this.searchLeaf.view) return;

		const searchView = this.searchLeaf.view;
		const searchContainer = searchView.containerEl;

		if (searchContainer) {
			// 保存原始父容器和原始样式
			this.originalParent = searchContainer.parentElement;

			// 保存原始样式以便恢复
			const originalStyles = {
				height: searchContainer.style.height,
				border: searchContainer.style.border,
				borderRadius: searchContainer.style.borderRadius,
				flex: searchContainer.style.flex,
				minHeight: searchContainer.style.minHeight,
				position: searchContainer.style.position,
				top: searchContainer.style.top,
				left: searchContainer.style.left,
				right: searchContainer.style.right,
				bottom: searchContainer.style.bottom
			};

			// 将原始样式保存到容器上，以便恢复时使用
			(searchContainer as any)._originalStyles = originalStyles;

			// 创建包装容器，完全占满模态框
			const wrapperDiv = contentEl.createDiv('search-wrapper');
			wrapperDiv.style.cssText = `
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				display: flex;
				flex-direction: column;
				background: var(--background-primary);
			`;

			// 添加搜索历史区域（固定在顶部）
			await this.createTopSearchHistory(wrapperDiv);

			// 隐藏搜索视图的标题栏（仅在模态框中）
			const header = searchContainer.querySelector('.view-header') as HTMLElement;
			let originalHeaderDisplay = '';
			if (header) {
				originalHeaderDisplay = header.style.display;
				header.style.display = 'none';
				(header as any)._originalDisplay = originalHeaderDisplay;
			}

			// 调整搜索容器的样式（仅在模态框中）
			searchContainer.style.position = 'relative';
			searchContainer.style.height = '100%';
			searchContainer.style.border = 'none';
			searchContainer.style.borderRadius = '0';
			searchContainer.style.flex = '1';
			searchContainer.style.minHeight = '0';
			searchContainer.style.top = '';
			searchContainer.style.left = '';
			searchContainer.style.right = '';
			searchContainer.style.bottom = '';

			// 移动搜索容器到wrapper中
			wrapperDiv.appendChild(searchContainer);

			// 禁用原生搜索历史和提示框
			this.disableNativeSearchFeatures(searchContainer);

			// 添加搜索历史功能
			this.addSearchHistoryEvents(searchContainer);
			this.addDoubleClickCloseEvents(searchContainer);

			this.searchViewContainer = searchContainer;
		}
	}
	private addDoubleClickCloseEvents(searchContainer: HTMLElement) {
		// 使用事件委托来处理动态生成的搜索结果
		const doubleClickHandler = (event: Event) => {
			const target = event.target as HTMLElement;

			// 检查是否双击了搜索结果项
			const resultItem = target.closest('.tree-item-self') ||
				target.closest('.search-result-file-title') ||
				target.closest('.search-result-container .tree-item');

			if (resultItem) {
				// 延迟关闭，确保文件打开操作完成
				setTimeout(() => {
					this.close();
				}, 100);
			}
		};

		searchContainer.addEventListener('dblclick', doubleClickHandler);

		// 也可以监听更具体的搜索结果元素
		const observeSearchResults = () => {
			const searchResultsContainer = searchContainer.querySelector('.search-results-container');
			if (searchResultsContainer) {
				// 使用 MutationObserver 监听搜索结果的动态变化
				const observer = new MutationObserver((mutations) => {
					mutations.forEach((mutation) => {
						if (mutation.type === 'childList') {
							// 为新添加的搜索结果添加双击事件
							mutation.addedNodes.forEach((node) => {
								if (node instanceof HTMLElement) {
									const resultElements = node.querySelectorAll('.tree-item-self, .search-result-file-title');
									resultElements.forEach(element => {
										// 避免重复添加事件监听器
										if (!(element as any)._doubleClickListenerAdded) {
											element.addEventListener('dblclick', () => {
												setTimeout(() => {
													this.close();
												}, 100);
											});
											(element as any)._doubleClickListenerAdded = true;
										}
									});
								}
							});
						}
					});
				});

				observer.observe(searchResultsContainer, {
					childList: true,
					subtree: true
				});

				// 保存 observer 以便在关闭时清理
				this.observers.push(observer);
			}
		};

		// 延迟执行以确保搜索结果容器已经创建
		setTimeout(observeSearchResults, 500);
	}

	// 新增方法：禁用原生搜索功能
	private disableNativeSearchFeatures(searchContainer: HTMLElement) {
		// 查找并隐藏原生的搜索历史下拉框
		const searchSuggestions = searchContainer.querySelectorAll('.suggestion-container, .search-suggestion, .search-suggestions');
		searchSuggestions.forEach((element) => {
			(element as HTMLElement).style.display = 'none';
		});

		// 查找并移除原生的历史记录按钮
		const historyButtons = searchContainer.querySelectorAll('[aria-label*="history"], [title*="history"], .search-history-button');
		historyButtons.forEach((button) => {
			(button as HTMLElement).style.display = 'none';
		});

		// 禁用搜索输入框的自动完成和历史记录
		const searchInput = searchContainer.querySelector('input') as HTMLInputElement;
		if (searchInput) {
			// 禁用浏览器自动完成
			searchInput.setAttribute('autocomplete', 'off');
			searchInput.setAttribute('autocorrect', 'off');
			searchInput.setAttribute('autocapitalize', 'off');
			searchInput.setAttribute('spellcheck', 'false');

			// 阻止原生的历史记录事件
			this.blockNativeHistoryEvents(searchInput);
		}

		// 隐藏可能的工具提示和弹框
		this.hideNativeTooltipsAndPopups(searchContainer);

		// 阻止键盘导航到历史记录
		this.blockNativeKeyboardNavigation(searchContainer);
	}

	// 阻止原生历史记录相关事件
	private blockNativeHistoryEvents(inputElement: HTMLInputElement) {
		const eventsToBlock = ['keydown', 'keyup', 'focus', 'blur', 'click'];

		eventsToBlock.forEach(eventType => {
			const originalHandlers: EventListener[] = [];

			// 创建一个包装函数来阻止特定的历史记录相关事件
			const blockingHandler = (e: Event) => {
				if (e instanceof KeyboardEvent) {
					// 阻止上下箭头键触发原生历史记录导航
					if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
						// 只有当没有建议框显示时才阻止
						const suggestionContainers = document.querySelectorAll('.suggestion-container, .search-suggestion');
						let hasSuggestions = false;
						suggestionContainers.forEach(container => {
							if ((container as HTMLElement).style.display !== 'none' &&
								(container as HTMLElement).offsetHeight > 0) {
								hasSuggestions = true;
							}
						});

						if (!hasSuggestions) {
							e.preventDefault();
							e.stopPropagation();
							e.stopImmediatePropagation();
						}
					}
				}
			};

			inputElement.addEventListener(eventType, blockingHandler, true);
			originalHandlers.push(blockingHandler);

			// 保存原始处理器以便恢复
			if (!this.originalEventHandlers.has(inputElement)) {
				this.originalEventHandlers.set(inputElement, []);
			}
			this.originalEventHandlers.get(inputElement)!.push({
				type: eventType,
				handler: blockingHandler
			});
		});
	}

	// 隐藏原生工具提示和弹框
	private hideNativeTooltipsAndPopups(searchContainer: HTMLElement) {
		// 使用 MutationObserver 监听 DOM 变化，隐藏可能出现的原生弹框
		const observer = new MutationObserver((mutations) => {
			mutations.forEach((mutation) => {
				if (mutation.type === 'childList') {
					mutation.addedNodes.forEach((node) => {
						if (node.nodeType === Node.ELEMENT_NODE) {
							const element = node as HTMLElement;

							// 隐藏各种可能的原生弹框和提示
							const selectors = [
								'.suggestion-container',
								'.search-suggestion',
								'.search-suggestions',
								'.tooltip',
								'.popover',
								'.dropdown',
								'[class*="suggestion"]',
								'[class*="dropdown"]',
								'[class*="popup"]',
								'[class*="tooltip"]'
							];

							selectors.forEach(selector => {
								if (element.matches && element.matches(selector)) {
									element.style.display = 'none';
								}
								element.querySelectorAll(selector).forEach(child => {
									(child as HTMLElement).style.display = 'none';
								});
							});
						}
					});
				}
			});
		});

		observer.observe(document.body, {
			childList: true,
			subtree: true
		});

		// 保存观察器以便后续清理
		this.observers.push(observer);
	}

	// 阻止原生键盘导航
	private blockNativeKeyboardNavigation(searchContainer: HTMLElement) {
		const keydownHandler = (e: KeyboardEvent) => {
			// 阻止可能触发原生历史记录的快捷键
			if (e.ctrlKey && e.key === 'h') { // Ctrl+H 可能触发历史记录
				e.preventDefault();
				e.stopPropagation();
			}

			// 阻止 F4 等可能的历史记录快捷键
			if (e.key === 'F4') {
				e.preventDefault();
				e.stopPropagation();
			}
		};

		searchContainer.addEventListener('keydown', keydownHandler, true);

		// 保存处理器
		if (!this.originalEventHandlers.has(searchContainer)) {
			this.originalEventHandlers.set(searchContainer, []);
		}
		this.originalEventHandlers.get(searchContainer)!.push({
			type: 'keydown',
			handler: keydownHandler
		});
	}

	private async createTopSearchHistory(parentEl: HTMLElement) {
		// 创建顶部搜索历史区域
		this.historyContainer = parentEl.createDiv('search-history-top');
		this.historyContainer.style.cssText = `
			background: var(--background-primary);
			border-bottom: 1px solid var(--background-modifier-border);
			padding: 4px 6px;
			flex-shrink: 0;
			max-height: 120px;
			overflow-y: auto;
			position: relative;
		`;

		// 创建内嵌关闭按钮
		const closeBtn = this.historyContainer.createDiv('inline-close-button');
		closeBtn.innerHTML = '×';
		closeBtn.style.cssText = `
			position: absolute;
			top: 4px;
			right: 6px;
			width: 20px;
			height: 20px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			font-size: 16px;
			color: var(--text-muted);
			background: var(--background-primary);
			border-radius: 50%;
			transition: all 0.2s;
			z-index: 20;
		`;

		closeBtn.addEventListener('mouseenter', () => {
			closeBtn.style.backgroundColor = 'var(--background-modifier-hover)';
			closeBtn.style.color = 'var(--text-normal)';
		});

		closeBtn.addEventListener('mouseleave', () => {
			closeBtn.style.backgroundColor = 'var(--background-primary)';
			closeBtn.style.color = 'var(--text-muted)';
		});

		closeBtn.addEventListener('click', () => {
			this.close();
		});

		// 创建历史记录列表容器 - 使用 flex 布局，给右侧关闭按钮留出空间
		const historyList = this.historyContainer.createDiv('search-history-list');
		historyList.style.cssText = `
			display: flex;
			flex-wrap: wrap;
			align-items: flex-start;
			gap: 3px;
			padding-right: 30px;
		`;

		// 渲染搜索历史
		await this.renderTopSearchHistory();
	}

	private async renderTopSearchHistory() {
		if (!this.historyContainer) return;

		const historyList = this.historyContainer.querySelector('.search-history-list') as HTMLElement;
		if (!historyList) return;

		const history = await this.historyManager.getHistory();
		historyList.empty();

		if (history.length === 0) {
			const emptyItem = historyList.createDiv('search-history-empty');
			emptyItem.textContent = '暂无搜索记录';
			emptyItem.style.cssText = `
				padding: 4px 0;
				color: var(--text-muted);
				font-size: 0.8em;
				width: 100%;
				text-align: center;
			`;
			return;
		}

		// 显示最近的20条记录（增加显示数量）
		const recentHistory = history.slice(0, 20);

		recentHistory.forEach((query, index) => {
			const tag = historyList.createDiv('search-history-tag');
			tag.style.cssText = `
				display: inline-flex;
				align-items: center;
				gap: 2px;
				padding: 2px 6px;
				background: var(--background-modifier-border);
				border-radius: 10px;
				font-size: 0.75em;
				cursor: pointer;
				transition: all 0.15s;
				max-width: 120px;
				margin-bottom: 2px;
				line-height: 1.2;
				position: relative;
			`;

			const textSpan = tag.createSpan();
			textSpan.textContent = query;
			textSpan.style.cssText = `
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				flex: 1;
			`;

			const deleteBtn = tag.createSpan('delete-btn');
			deleteBtn.textContent = '×';
			deleteBtn.style.cssText = `
				position: absolute;
				top: -6px;
				right: -6px;
				color: var(--text-on-accent);
				background: var(--interactive-accent);
				font-size: 10px;
				line-height: 1;
				padding: 0;
				border-radius: 50%;
				display: none;
				width: 14px;
				height: 14px;
				text-align: center;
				cursor: pointer;
				z-index: 10;
				box-shadow: 0 1px 3px rgba(0,0,0,0.2);
			`;

			// 鼠标悬停效果
			tag.addEventListener('mouseenter', () => {
				tag.style.backgroundColor = 'var(--background-modifier-hover)';
				tag.style.transform = 'scale(1.02)';
				tag.style.paddingRight = '8px'; // 为×号留出空间
				deleteBtn.style.display = 'flex';
				deleteBtn.style.alignItems = 'center';
				deleteBtn.style.justifyContent = 'center';
			});
			tag.addEventListener('mouseleave', () => {
				tag.style.backgroundColor = 'var(--background-modifier-border)';
				tag.style.transform = 'scale(1)';
				tag.style.paddingRight = '6px';
				deleteBtn.style.display = 'none';
			});

			// 点击标签进行搜索
			textSpan.addEventListener('click', async (e) => {
				e.stopPropagation();
				if (this.searchInputElement) {
					this.searchInputElement.value = query;
					this.searchInputElement.dispatchEvent(new Event('input', { bubbles: true }));
					this.searchInputElement.focus();
					// 将此搜索移到历史顶部
					await this.historyManager.addSearch(query);
					await this.renderTopSearchHistory();
				}
			});

			// 删除历史项
			deleteBtn.addEventListener('click', async (e) => {
				e.stopPropagation();
				await this.historyManager.removeFromHistory(query);
				await this.renderTopSearchHistory();
			});
		});

		// 在历史记录标签的最后添加清空按钮
		if (history.length > 0) {
			const clearBtn = historyList.createSpan('clear-history-btn');
			clearBtn.textContent = '清空';
			clearBtn.style.cssText = `
				display: inline-flex;
				align-items: center;
				padding: 2px 6px;
				font-size: 0.75em;
				color: var(--text-muted);
				cursor: pointer;
				border-radius: 10px;
				transition: all 0.15s;
				border: 1px solid var(--background-modifier-border);
				background: var(--background-primary);
				line-height: 1.2;
			`;

			clearBtn.addEventListener('mouseenter', () => {
				clearBtn.style.backgroundColor = 'var(--background-modifier-hover)';
				clearBtn.style.color = 'var(--text-normal)';
				clearBtn.style.borderColor = 'var(--background-modifier-hover)';
			});
			clearBtn.addEventListener('mouseleave', () => {
				clearBtn.style.backgroundColor = 'var(--background-primary)';
				clearBtn.style.color = 'var(--text-muted)';
				clearBtn.style.borderColor = 'var(--background-modifier-border)';
			});
			clearBtn.addEventListener('click', async () => {
				await this.historyManager.clearHistory();
				await this.renderTopSearchHistory();
			});
		}
	}

	private addSearchHistoryEvents(searchContainer: HTMLElement) {
		// 获取搜索输入框
		this.searchInputElement = searchContainer.querySelector('input') as HTMLInputElement;

		if (this.searchInputElement) {
			const originalInput = this.searchInputElement;

			// 监听键盘事件 - 只在按下回车键时保存历史记录
			originalInput.addEventListener('keydown', async (e) => {
				if (e.key === 'Enter') {
					const query = (e.target as HTMLInputElement).value.trim();
					if (query) {
						// 立即保存搜索历史
						await this.historyManager.addSearch(query);
						await this.renderTopSearchHistory();
					}
				}
			});

			// 确保搜索输入框可以获得焦点
			setTimeout(() => {
				originalInput.focus();
			}, 100);
		}
	}

	private async renderSearchHistory() {
		// 这个方法已被 renderTopSearchHistory 替代
		await this.renderTopSearchHistory();
	}

	private showHistory() {
		// 顶部历史记录始终显示，不需要切换
	}

	private hideHistory() {
		// 顶部历史记录始终显示，不需要切换
	}

	private navigateHistory(direction: 'up' | 'down') {
		// 顶部历史记录使用点击方式，不需要键盘导航
	}

	private showError(contentEl: HTMLElement, error: any) {
		contentEl.empty();
		const errorDiv = contentEl.createDiv("search-error");
		errorDiv.createEl("h3", { text: "无法加载搜索功能" });
		errorDiv.createEl("p", { text: `错误: ${error.message || error}` });
		errorDiv.createEl("p", {
			text: "请尝试先在左侧面板打开搜索功能，然后重新使用此命令。"
		});

		// 提供备用按钮
		const fallbackBtn = errorDiv.createEl("button", {
			text: "打开左侧搜索面板",
			cls: "mod-cta"
		});

		fallbackBtn.addEventListener("click", () => {
			this.app.workspace.getLeftLeaf(false).setViewState({
				type: 'search',
				active: true
			});
			this.close();
		});
	}

	onClose() {
		// 清理所有观察器
		this.observers.forEach(observer => {
			if (observer && observer.disconnect) {
				observer.disconnect();
			}
		});
		this.observers = [];

		// 恢复搜索视图到原始位置
		this.restoreSearchView();

		// 清理事件处理器
		this.cleanupEventHandlers();

		const {contentEl} = this;
		contentEl.empty();
	}

	// 清理添加的事件处理器
	private cleanupEventHandlers() {
		this.originalEventHandlers.forEach((handlers, element) => {
			handlers.forEach(({type, handler}) => {
				element.removeEventListener(type, handler, true);
			});
		});
		this.originalEventHandlers.clear();
	}

	private restoreSearchView() {
		if (this.searchViewContainer) {
			// 恢复标题栏显示
			const header = this.searchViewContainer.querySelector('.view-header') as HTMLElement;
			if (header && (header as any)._originalDisplay !== undefined) {
				header.style.display = (header as any)._originalDisplay || '';
				delete (header as any)._originalDisplay;
			}

			// 恢复原始样式
			const originalStyles = (this.searchViewContainer as any)._originalStyles;
			if (originalStyles) {
				Object.keys(originalStyles).forEach(key => {
					(this.searchViewContainer!.style as any)[key] = originalStyles[key] || '';
				});
				delete (this.searchViewContainer as any)._originalStyles;
			}

			// 移回原始父容器
			if (this.originalParent) {
				this.originalParent.appendChild(this.searchViewContainer);
			}
		}

		if (this.searchLeaf && !this.originalParent) {
			// 如果是新创建的搜索视图，清理它
			this.searchLeaf.detach();
		}

		// 重置状态
		this.searchLeaf = null;
		this.originalParent = null;
		this.searchViewContainer = null;
		this.historyContainer = null;
		this.searchInputElement = null;
	}
}

// 备用方案：通过CSS选择器直接操作DOM - 也改为持久化存储
export class AlternativeNativeSearchModal extends Modal {
	private searchClone: HTMLElement | null = null;
	private historyManager: SearchHistoryManager;
	private plugin: MyPlugin;
	private observers: (MutationObserver | any)[] = []; // 用于存储所有观察器

	constructor(app: App, plugin: MyPlugin) {
		super(app);
		this.plugin = plugin;
		this.setTitle(""); // 移除标题
		this.modalEl.addClass("alternative-search-modal");
		this.historyManager = new SearchHistoryManager(app, plugin);
	}

	onOpen() {
		const {contentEl} = this;

		// 设置模态框大小
		this.modalEl.style.width = "850px";
		this.modalEl.style.height = "650px";
		this.modalEl.style.maxWidth = "95vw";
		this.modalEl.style.maxHeight = "90vh";
		contentEl.style.padding = "0";
		contentEl.style.height = "100%";

		this.cloneSearchInterface(contentEl);
	}

	private cloneSearchInterface(contentEl: HTMLElement) {
		// 查找现有的搜索面板
		const searchPane = document.querySelector('.workspace-leaf-content[data-type="search"]') as HTMLElement;

		if (searchPane) {
			// 克隆搜索面板
			this.searchClone = searchPane.cloneNode(true) as HTMLElement;

			// 移除标题栏
			const header = this.searchClone.querySelector('.view-header');
			if (header) {
				header.remove();
			}

			// 调整样式
			this.searchClone.style.height = '100%';
			this.searchClone.style.border = 'none';

			// 禁用克隆版本中的原生搜索功能
			this.disableNativeSearchFeaturesInClone(this.searchClone);

			// 添加到模态框
			contentEl.appendChild(this.searchClone);

			// 重新绑定事件
			this.rebindSearchEvents();
			this.addDoubleClickCloseEvents();

			// 聚焦搜索输入
			setTimeout(() => {
				const input = this.searchClone?.querySelector('.search-input-container input') as HTMLInputElement;
				if (input) {
					input.focus();
				}
			}, 100);

		} else {
			// 如果没找到搜索面板，提示用户
			this.showNoSearchPaneMessage(contentEl);
		}
	}

	// 在克隆的搜索面板中禁用原生功能
	private disableNativeSearchFeaturesInClone(clonedContainer: HTMLElement) {
		// 隐藏所有可能的建议容器
		const suggestionElements = clonedContainer.querySelectorAll(
			'.suggestion-container, .search-suggestion, .search-suggestions, [class*="suggestion"]'
		);
		suggestionElements.forEach((element) => {
			(element as HTMLElement).style.display = 'none';
			(element as HTMLElement).remove(); // 直接移除
		});

		// 隐藏历史记录相关按钮
		const historyElements = clonedContainer.querySelectorAll(
			'[aria-label*="history"], [title*="history"], .search-history-button, [class*="history"]'
		);
		historyElements.forEach((element) => {
			(element as HTMLElement).style.display = 'none';
			(element as HTMLElement).remove(); // 直接移除
		});

		// 处理搜索输入框
		const searchInput = clonedContainer.querySelector('input') as HTMLInputElement;
		if (searchInput) {
			// 禁用各种自动完成功能
			searchInput.setAttribute('autocomplete', 'off');
			searchInput.setAttribute('autocorrect', 'off');
			searchInput.setAttribute('autocapitalize', 'off');
			searchInput.setAttribute('spellcheck', 'false');

			// 移除可能的 list 属性（关联 datalist）
			searchInput.removeAttribute('list');
		}

		// 移除所有 datalist 元素
		const datalists = clonedContainer.querySelectorAll('datalist');
		datalists.forEach(datalist => datalist.remove());
	}

	private addDoubleClickCloseEvents() {
		if (!this.searchClone) return;

		// 为搜索结果添加双击关闭事件
		this.searchClone.addEventListener('dblclick', (event) => {
			const target = event.target as HTMLElement;

			// 检查是否双击了搜索结果项
			const resultItem = target.closest('.tree-item-self') ||
				target.closest('.search-result-file-title') ||
				target.closest('.search-result-container .tree-item');

			if (resultItem) {
				// 延迟关闭，确保文件打开操作完成
				setTimeout(() => {
					this.close();
				}, 100);
			}
		});
	}

	private rebindSearchEvents() {
		if (!this.searchClone) return;

		// 重新绑定搜索输入事件
		const searchInput = this.searchClone.querySelector('.search-input-container input') as HTMLInputElement;
		if (searchInput) {
			// 阻止原有的事件处理器
			const newInput = searchInput.cloneNode(true) as HTMLInputElement;
			searchInput.parentNode?.replaceChild(newInput, searchInput);

			// 监听输入事件（用于触发搜索）
			newInput.addEventListener('input', (e) => {
				const query = (e.target as HTMLInputElement).value;
				// 触发原始搜索功能
				this.triggerSearch(query);
			});

			// 监听回车键事件（用于保存历史记录）
			newInput.addEventListener('keydown', async (e) => {
				if (e.key === 'Enter') {
					const query = (e.target as HTMLInputElement).value.trim();
					if (query) {
						// 保存搜索历史
						await this.historyManager.addSearch(query);
					}
				}

				// 阻止可能触发原生历史记录的键盘事件
				if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
					// 检查是否有我们自己的建议框，如果没有就阻止
					const suggestionContainers = document.querySelectorAll('.suggestion-container, .search-suggestion');
					let hasSuggestions = false;
					suggestionContainers.forEach(container => {
						if ((container as HTMLElement).style.display !== 'none' &&
							(container as HTMLElement).offsetHeight > 0) {
							hasSuggestions = true;
						}
					});

					if (!hasSuggestions) {
						e.preventDefault();
						e.stopPropagation();
					}
				}
			});
		}

		// 重新绑定结果点击事件
		const resultElements = this.searchClone.querySelectorAll('.tree-item');
		resultElements.forEach(element => {
			element.addEventListener('click', (e) => {
				// 处理结果点击
				this.handleResultClick(e);
			});
		});
	}

	private triggerSearch(query: string) {
		// 在原始搜索面板中触发搜索
		const originalSearchPane = document.querySelector('.workspace-leaf-content[data-type="search"]');
		if (originalSearchPane) {
			const originalInput = originalSearchPane.querySelector('.search-input-container input') as HTMLInputElement;
			if (originalInput) {
				originalInput.value = query;
				originalInput.dispatchEvent(new Event('input', { bubbles: true }));

				// 等待一段时间后更新我们的克隆
				setTimeout(() => {
					this.updateClonedResults();
				}, 500);
			}
		}
	}

	private updateClonedResults() {
		if (!this.searchClone) return;

		const originalSearchPane = document.querySelector('.workspace-leaf-content[data-type="search"]');
		if (originalSearchPane) {
			const originalResults = originalSearchPane.querySelector('.search-results-container');
			const clonedResults = this.searchClone.querySelector('.search-results-container');

			if (originalResults && clonedResults) {
				clonedResults.innerHTML = originalResults.innerHTML;
				this.rebindResultEvents();
			}
		}
	}

	private rebindResultEvents() {
		if (!this.searchClone) return;

		const resultElements = this.searchClone.querySelectorAll('.tree-item-self');
		resultElements.forEach(element => {
			element.addEventListener('click', (e) => {
				this.handleResultClick(e);
			});
		});
	}

	private handleResultClick(e: Event) {
		const target = e.target as HTMLElement;
		const resultItem = target.closest('.tree-item-self');

		if (resultItem) {
			// 模拟在原始搜索面板中的点击
			const originalSearchPane = document.querySelector('.workspace-leaf-content[data-type="search"]');
			if (originalSearchPane) {
				const correspondingItem = originalSearchPane.querySelector(`.tree-item-self[data-path="${resultItem.getAttribute('data-path')}"]`) as HTMLElement;
				if (correspondingItem) {
					correspondingItem.click();
					this.close(); // 关闭模态框
				}
			}
		}
	}

	private showNoSearchPaneMessage(contentEl: HTMLElement) {
		const messageDiv = contentEl.createDiv("no-search-message");
		messageDiv.createEl("h3", { text: "搜索面板未找到" });
		messageDiv.createEl("p", { text: "请先在左侧面板中打开搜索功能，然后重新运行此命令。" });

		const openSearchBtn = messageDiv.createEl("button", {
			text: "打开搜索面板",
			cls: "mod-cta"
		});

		openSearchBtn.addEventListener("click", async () => {
			await this.app.workspace.getLeftLeaf(false).setViewState({
				type: 'search',
				active: true
			});
			this.close();
		});
	}

	onClose() {
		// 清理所有观察器
		this.observers.forEach(observer => {
			if (observer && observer.disconnect) {
				observer.disconnect();
			}
		});
		this.observers = [];

		const {contentEl} = this;
		contentEl.empty();
		this.searchClone = null;
	}
}
